import json
from rest_framework import serializers
from ..models.Institution import Institution
from ..utils.literUtils import emptyValue

# 查询内容序列化
class InstListQuerySerializer(serializers.Serializer):
    name = serializers.CharField(required=False,allow_blank=True)
    zh_name = serializers.CharField(required=False,allow_blank=True)
    ins_code = serializers.CharField(required=False,allow_blank=True)
    city = serializers.CharField(required=False,allow_blank=True)
    country = serializers.CharField(required=False,allow_blank=True)
    address = serializers.CharField(required=False,allow_blank=True)
    postal_code = serializers.CharField(required=False,allow_blank=True)
    email = serializers.CharField(required=False,allow_blank=True)
    contact_number = serializers.CharField(required=False,allow_blank=True)
    website = serializers.CharField(required=False,allow_blank=True)
    founded_date = serializers.CharField(required=False,allow_blank=True)
    description = serializers.CharField(required=False,allow_blank=True)
    inst_type = serializers.ListField(required=False)
    departments = serializers.CharField(required=False,allow_blank=True)

    page_size = serializers.IntegerField(
        required=False, max_value=50, min_value=1)
    current_page = serializers.IntegerField(required=False)
    sort_prop = serializers.CharField(required=False,allow_blank=True)
    sort_order = serializers.CharField(required=False,allow_blank=True)

    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "name" in attrs:
            attrs["name"] = attrs["name"].strip()
            if attrs["name"] == "": attrs.pop("name")
        if "zh_name" in attrs:
            attrs["zh_name"] = attrs["zh_name"].strip()
            if attrs["zh_name"] == "": attrs.pop("zh_name")
        if "ins_code" in attrs:
            attrs["ins_code"] = attrs["ins_code"].strip()
            if attrs["ins_code"] == "": attrs.pop("ins_code")
        if "city" in attrs:
            attrs["city"] = attrs["city"].strip()
            if attrs["city"] == "": attrs.pop("city")
        if "country" in attrs:
            attrs["country"] = attrs["country"].strip()
            if attrs["country"] == "": attrs.pop("country")
        if "address" in attrs:
            attrs["address"] = attrs["address"].strip()
            if attrs["address"] == "": attrs.pop("address")
        if "postal_code" in attrs:
            attrs["postal_code"] = attrs["postal_code"].strip()
            if attrs["postal_code"] == "": attrs.pop("postal_code")
        if "email" in attrs:
            attrs["email"] = attrs["email"].strip()
            if attrs["email"] == "": attrs.pop("email")
        if "contact_number" in attrs:
            attrs["contact_number"] = attrs["contact_number"].strip()
            if attrs["contact_number"] == "": attrs.pop("contact_number")
        if "website" in attrs:
            attrs["website"] = attrs["website"].strip()
            if attrs["website"] == "": attrs.pop("website")
        if "founded_date" in attrs:
            attrs["founded_date"] = attrs["founded_date"].strip()
            if attrs["founded_date"] == "": attrs.pop("founded_date")
        if "description" in attrs:
            attrs["description"] = attrs["description"].strip()
            if attrs["description"] == "": attrs.pop("description")
        if "departments" in attrs:
            attrs["departments"] = attrs["departments"].strip()
            if attrs["departments"] == "": attrs.pop("departments")
        if "inst_type" in attrs:
            if len(attrs["inst_type"]) == 0: attrs.pop("inst_type")
        if ("name" not in attrs or attrs["name"] == "") and ("zh_name" not in attrs or attrs["zh_name"] == "") and\
           ("ins_code" not in attrs or attrs["ins_code"] == "") and ("postal_code" not in attrs or attrs["postal_code"] == "") and\
           ("country" not in attrs or attrs["country"] == "") and ("city" not in attrs or attrs["city"] == "")  and\
           ("address" not in attrs or attrs["address"] == "") and ("email" not in attrs or attrs["email"] == "") and\
           ("departments" not in attrs or attrs["departments"] == "") and ("inst_type" not in attrs or len(attrs["inst_type"]) == 0)  and\
           ("contact_number" not in attrs or attrs["contact_number"] == "") and ("website" not in attrs or attrs["website"] == "")  and\
           ("founded_date" not in attrs or attrs["founded_date"] == "") and ("description" not in attrs or attrs["description"] == ""):
            filter_flag = False
        if ("page_size" not in attrs):
            page_flag = False
        else:
            if "current_page" not in attrs:
                attrs["current_page"] = 1
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs
    
    @classmethod
    def get_query_fields(self):
        return [{"title":"名称：", "dataIndex":"name", "type":"CharField"},
                {"title":"中文名：", "dataIndex":"zh_name", "type":"CharField"},
                {"title":"标识代码：", "dataIndex":"ins_code", "type":"CharField"},
                {"title":"所在国家：", "dataIndex":"country", "type":"CharField"},
                {"title":"所在城市：", "dataIndex":"city", "type":"CharField"},
                {"title":"详细地址：", "dataIndex":"address", "type":"CharField"},
                {"title":"邮政编码：", "dataIndex":"postal_code", "type":"CharField"},
                {"title":"联系邮箱：", "dataIndex":"email", "type":"CharField"},
                {"title":"联系电话：", "dataIndex":"contact_number", "type":"CharField"},
                {"title":"官方网站：", "dataIndex":"website", "type":"CharField"},
                {"title":"创立日期：", "dataIndex":"founded_date", "type":"CharField"},
                {"title":"所属类别：", "dataIndex":"inst_type", "type":"ForeignKey"},
                {"title":"描述：", "dataIndex":"description", "type":"CharField"},
                {"title":"部门：", "dataIndex":"departments", "type":"ManyToManyField"},]
        
        
# 用于输出查询时的数据


class InstListSerializer(serializers.ModelSerializer):
    inst_type = serializers.SerializerMethodField()
    departments = serializers.SerializerMethodField()

    class Meta:
        model = Institution
        fields = ['uuid', 'name', 'zh_name', 'ins_code', 'city', 'country', 'contact_number',\
                  "postal_code", "address", "email", "website", "founded_date", 'description',\
                  'inst_type', 'departments']
        
    def get_inst_type(self, obj): # obj: Literature类实例
        return "{}({})".format(obj.inst_type.zh_name, obj.inst_type.name) + "\n"
    
    def get_departments(self, obj):
        departments_content = ""
        for department in obj.department_set.all():
            if emptyValue(department.zh_name):
                departments_content += department.name + "; "
            else:
                departments_content += department.name + ' (' + department.zh_name + '); '
        return departments_content[:-2]
    
    @classmethod
    def get_extra_fields_info(self):
        return [{"title":"所属类别", "dataIndex":"inst_type", "type":"CharField"},
                {"title":"部门", "dataIndex":"departments", "type":"CharField"},]